import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../utils/json_utils.dart';
import '../../../utils/themes/app_theme_extension.dart';

/// JSON测试页面，用于测试解析复杂的JSON数据
class JsonTestView extends StatefulWidget {
  const JsonTestView({Key? key}) : super(key: key);

  @override
  _JsonTestViewState createState() => _JsonTestViewState();
}

class _JsonTestViewState extends State<JsonTestView> {
  final TextEditingController _controller = TextEditingController();
  Map<String, dynamic> _parsedJson = {};
  String _errorMessage = '';
  bool _hasParsed = false;

  @override
  void initState() {
    super.initState();
    
    // 检查是否有传入的JSON数据
    Future.delayed(Duration.zero, () {
      final arguments = Get.arguments;
      if (arguments != null && arguments is Map<String, dynamic> && arguments.containsKey('jsonData')) {
        _controller.text = arguments['jsonData'].toString();
        // 自动解析传入的JSON
        _parseJson();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _parseJson() {
    setState(() {
      _errorMessage = '';
      _parsedJson = {};
      _hasParsed = true;

      try {
        final jsonString = _controller.text.trim();
        if (jsonString.isEmpty) {
          _errorMessage = '请输入JSON数据';
          return;
        }

        // 使用JsonUtils解析带转义字符的JSON
        _parsedJson = JsonUtils.parseEscapedJsonString(jsonString);
        
        // 尝试检测是否为物模型格式
        if (_isThingModelJson(_parsedJson)) {
          _showThingModelInfo(_parsedJson);
        }
      } catch (e) {
        _errorMessage = '解析失败: $e';
        print('解析JSON失败: $e');
      }
    });
  }
  
  // 检测是否为物模型JSON
  bool _isThingModelJson(Map<String, dynamic> json) {
    // 物模型通常包含这三个字段中的至少一个
    return json.containsKey('properties') || 
           json.containsKey('services') || 
           json.containsKey('events');
  }
  
  // 显示物模型信息
  void _showThingModelInfo(Map<String, dynamic> json) {
    int propertiesCount = 0;
    int servicesCount = 0;
    int eventsCount = 0;
    
    if (json.containsKey('properties') && json['properties'] is List) {
      propertiesCount = (json['properties'] as List).length;
    }
    
    if (json.containsKey('services') && json['services'] is List) {
      servicesCount = (json['services'] as List).length;
    }
    
    if (json.containsKey('events') && json['events'] is List) {
      eventsCount = (json['events'] as List).length;
    }
    
    Get.snackbar(
      '物模型解析成功', 
      '包含 $propertiesCount 个属性, $servicesCount 个服务, $eventsCount 个事件',
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 3),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();

    return Scaffold(
      appBar: AppBar(
        title: const Text('JSON解析测试'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'JSON数据输入',
                      style: theme.textTheme.titleMedium,
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _controller,
                      maxLines: 8,
                      decoration: InputDecoration(
                        hintText: '粘贴带转义字符的JSON数据...',
                        border: const OutlineInputBorder(),
                        filled: true,
                        fillColor: extension?.cardBackground,
                      ),
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _parseJson,
                      child: const Text('解析JSON'),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '解析结果',
                        style: theme.textTheme.titleMedium,
                      ),
                      const SizedBox(height: 8),
                      if (_errorMessage.isNotEmpty)
                        Text(
                          _errorMessage,
                          style: const TextStyle(color: Colors.red),
                        )
                      else if (!_hasParsed)
                        const Text('请先输入并解析JSON数据')
                      else
                        Expanded(
                          child: SingleChildScrollView(
                            child: Text(
                              JsonUtils.formatJsonString(_parsedJson),
                              style: const TextStyle(fontFamily: 'monospace'),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
} 